/*
 * PGN_Reader : A simple pgn reader for chess games.
 * Copyright (C) 2011 Laurent BERNABE
 * 
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package com.gmail.bernabe.laurent.java_swing.pgn_reader.gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;

import javax.swing.JPanel;

import com.gmail.bernabe.laurent.java_swing.pgn_reader.processing.move.BoardCell;
import com.gmail.bernabe.laurent.java_swing.pgn_reader.processing.piece.Piece;

public class BoardJPanel extends JPanel {
	
	public final static int CELL_DIMENSION = 50;
	public final static int PIECE_DIMENSION = 40;
	
	public BoardJPanel(PGNReaderFrame pgnFrame){
		setPreferredSize(new Dimension(400, 400));
		this.pgnFrame = pgnFrame;
		piecesValues = loadPiecesFrom_FEN_Position(classicStartFEN);
	}

	@Override
	public void paint(Graphics graphics) {
		paintTheCells(graphics);
		for(int cellLine=0; cellLine<8; cellLine++){
			for(int cellColumn=0; cellColumn<8; cellColumn++){
				paintAPieceByCellPosition(graphics, new BoardCell(cellLine, cellColumn));
			}
		}
		if (pieceToAnimate != null){
			paintAPieceByAbsolutePosition(graphics, pieceToAnimate.getPieceValue(),
					pieceToAnimate.getCurrentX() , pieceToAnimate.getCurrentY());
		}
	}
	
	/*
	 * Be carefull !!!
	 * line = 0 is black lowest rank !!! (the line of black pieces)
	 */
	public void animateThenRegister(final BoardCell startCell, final BoardCell endCell) {
		/* If an animation is already started, waits for it to finish.
		 * (such as in roques moves : 2 animations
		 * are requested at the same time)
		 */
		if (pieceToAnimate != null){
			if (pieceToAnimate.getAnimatorThread() != null){
				try {
					pieceToAnimate.getAnimatorThread().join();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		// Animating
		final Piece pieceToMove = piecesValues[startCell.cellLine][startCell.cellColumn];
		pieceToAnimate = new PieceToAnimate(pieceToMove, this);
		pieceToAnimate.setStartPosition(startCell);
		pieceToAnimate.setEndPosition(endCell);
		pgnFrame.getButtonsPanel().setEnabled(false);
		pieceToAnimate.animate();
		// Registering
		piecesValues[startCell.cellLine][startCell.cellColumn] = 
			null;
		Thread registeringThread = new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					pieceToAnimate.getAnimatorThread().join();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

				piecesValues[endCell.cellLine][endCell.cellColumn] = pieceToMove;
				pgnFrame.getButtonsPanel().setEnabled(true);
			}

		});
		registeringThread.start();
	}

	public Piece getPieceAt(BoardCell wantedCell) {
		return piecesValues[wantedCell.cellLine][wantedCell.cellColumn];
	}
	
	public static int getPieceAbsolutePosition(int cellColumnOrLine) {
		return cellColumnOrLine*CELL_DIMENSION+(CELL_DIMENSION - PIECE_DIMENSION)/2;
	}
	
	private void paintAPieceByAbsolutePosition(Graphics graphics, Piece pieceToDraw,
			int positionX, int positionY){
		if (pieceToDraw != null) {
			Image piecePicture =  PiecesImages.getInstance().getPieceImage(pieceToDraw)
					.getScaledInstance(PIECE_DIMENSION, PIECE_DIMENSION, Image.SCALE_FAST);
			graphics.drawImage(piecePicture,
					positionX,
					positionY,
					this);
		}
	}
	
	private void paintAPieceByCellPosition(Graphics graphics, BoardCell cellPosition) {
		Piece pieceToDraw = piecesValues[cellPosition.cellLine][cellPosition.cellColumn];
		paintAPieceByAbsolutePosition(graphics, pieceToDraw, 
				getPieceAbsolutePosition(cellPosition.cellColumn),
				getPieceAbsolutePosition(7-cellPosition.cellLine));
	}
	
	private void paintTheCells(Graphics graphics) {
		for (int line = 0; line < 8; line++){
			for (int column = 0; column < 8; column++){
				Color cellColor;
				if ((line+column)%2 == 0)
					cellColor = WHITE_CELL_COLOR;
				else
					cellColor = BLACK_CELL_COLOR;
				paintACell(graphics, line, column, cellColor);
			}
		}
	}

	private void paintACell(Graphics graphics, int line, int column,
			Color cellColor) {
		int posX = line * CELL_DIMENSION;
		int posY = column * CELL_DIMENSION;
		graphics.setColor(cellColor);
		graphics.fillRect(posX, posY, CELL_DIMENSION, CELL_DIMENSION);
	}
	
	private Piece[][] loadPiecesFrom_FEN_Position(String fenPosition) {
		Piece[][] piecesValuesToReturn = new Piece[8][8];
	    String [] piecesLines = fenPosition.split(" ")[0].split("/");
	    for(int cellLine=0; cellLine<8; cellLine++){
	    	String currentPiecesLine = piecesLines[cellLine];
	    	int cellColumn = 0;
	    	int indexInThisLine_FEN_Pos = 0;
			do {
				Character currentFENValue = currentPiecesLine.charAt(indexInThisLine_FEN_Pos);
				if (Character.isDigit(currentFENValue)) {
					int emptySpacesNumber = currentFENValue.compareTo('0');
					for (int skipCellNumber=0; skipCellNumber<emptySpacesNumber; skipCellNumber++){
						piecesValuesToReturn[7-cellLine][cellColumn] = null;
						cellColumn ++;
					}
					indexInThisLine_FEN_Pos++;
				}
				else {
					piecesValuesToReturn[7-cellLine][cellColumn] = new Piece(currentFENValue);
					cellColumn++;
					indexInThisLine_FEN_Pos++;
				}
	    	} while(cellColumn < 8);
	    }
	    return piecesValuesToReturn;
	}

	private static final long serialVersionUID = 1L;
	private static final String classicStartFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR";
	private final static Color WHITE_CELL_COLOR = new Color(255,255,160);
	private final static Color BLACK_CELL_COLOR = new Color(70,35,20);
	// first dimension is for lines and line = 0 is white lowest rank
	private Piece [][] piecesValues;
	private PieceToAnimate pieceToAnimate = null;
	
	private PGNReaderFrame pgnFrame;

}
